from wxpy import *
import re
import requests
import time

bot = Bot()
myself = bot.self
# 这是一个log对象
logger = get_wechat_logger(myself)
tuling = Tuling(api_key='6a9349d66f77442cb049232e400f1aeb')

base_url = r"http://127.0.0.1:9095/api/item/matpwd"

def get_tpwd(key_word):
    try:
        url = "{}?q={}".format(base_url, key_word)
        response = requests.get(url)
        res_json = response.json()
        if 'error' in res_json.keys():
            return None
        elif 'tpwd_list' in res_json.keys():
            return res_json['tpwd_list']
        return None
    except Exception as e:
        logger.exception('出现异常：{}'.format(e))
    

def send_tpwd(tpwd_list, sender):
    if tpwd_list:
        for tpwd in tpwd_list:
            tpwd_str = tpwd['tpwd_str']
            sender.send(tpwd_str)
            time.sleep(1)
            # print(tpwd['tpwd_str'])
    else:
        sender.send('没有找到对应的优惠券')

@bot.register(Friend, msg_types = TEXT)
def process_tbk_message(msg):
    try:
        # if msg.sender.name == '小不点':
        #     tuling.do_reply(msg)
        if '找券' in msg.text:
            key_word_arr = msg.text.split('=')
            if len(key_word_arr) > 1:
                key_word = key_word_arr[1]
                tpwd_list = get_tpwd(key_word)
                send_tpwd(tpwd_list, msg.sender)
            else:
                return '输入查询格式不正确'
        return
    except ResponseError as e:
        logger.exception('异常码：{}，异常信息：{}'.format(e.err_code, e.err_msg))



# 最后阻塞线程，用于监听收到的消息
# bot.join()
embed()